/**
 *挖掘分析
 */
define("func/wjAnalysis", [
    "leaflet",
    "leaflet/heatmap",
    "func/base",
    "data/ajax",
    "func/fxpg"

], function(L, HeatmapOverlay) {

    L.ICT.Func.add("WJAnalysis", {

        Class: L.Class.extend({

            initialize: function() {
                this.menu = L.ict.app.menu;
                this.menuid = "ict_menu_main_xwwj";
                this.ictmap = L.ict.app.ictmap;
                this.config = Project_ParamConfig.wjAnalysisConfig;
                this.ajax = new L.ICT.Ajax();

                this._layer = null;
                this._curtype = null;
                this._ssfblayergroup = null;
                this._activeForecateLayer = null;
                this.fxpgObj = null;

            },

            start: function() {
                this.menu.mainmenu.deactiveOtherSubMenu(this.menuid);
                this.menu.mainmenu.deactivePortInfo();
                if (this.menu.submenu.has(this.menuid)) {
                    this.menu.submenu.destory(this.menuid);
                }
                this.menu.submenu.add(this.menuid, this.getSubMenuHTML());
                this.menu.submenu.show(this.menuid);
                this._initSubMenuEvts();
            },

            stop: function() {
                this.menu.submenu.hide();
                this.removeLayer();
                if (this.fxpgObj) {
                    this.fxpgObj.stop();
                    this.fxpgObj = null;
                }
                this.ictmap.realtarget.addRealTargetLayer();
                this.ictmap.OperateState.wjfx = false;
                this.menu.mainmenu.deactiveMenu(this.menuid);
            },

            getSubMenuHTML: function() {
                var html = [];

                //交通模式
                html.push('<div class="submenu_wjanalysis">');
                html.push('<div class="submenu_wjanalysis_jtms">');
                html.push('<label><img src="themes/images/frame/menu_xwfx_skfx.png">&nbsp&nbsp交通模式</label>');
                html.push('<ul>');
                //密度分布
                html.push('<li class="submenu_li submenu_li_mdfb"><label>密度分布</label></li>');
                //流量分布
                html.push('<li class="submenu_li submenu_li_llfb"><label>流量分布</label></li>');
                //速度分布
                html.push('<li class="submenu_li submenu_li_sdfb"><label>速度分布</label></li>');
                //失事分布
                html.push('<li class="submenu_li submenu_li_ssfb"><label>失事分布</label></li>');
                html.push('</ul>');
                html.push('</div>');

                //预测评估
                html.push('<div class="submenu_wjanalysis_ycpg">');
                html.push('<label><img src="themes/images/frame/menu_xwfx_ycpg.png">&nbsp&nbsp预测评估</label>');
                html.push('<ul>');
                html.push('<li class="submenu_li submenu_li_hdyc"><label>活动预测</label></li>');
                html.push('<li class="submenu_li submenu_li_fxpg"><label>风险评估</label></li>');
                html.push('</ul>');
                html.push('</div>');
                html.push('</div>');

                return html.join("");
            },

            _initSubMenuEvts: function() {
                var $menuContainer = this.menu.getContainer(),
                    self = this;

                //密度分布
                $menuContainer.find(".submenu_wjanalysis .submenu_li_mdfb").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.ictmap.realtarget.addRealTargetLayer();
                        self.ictmap.OperateState.wjfx = false;
                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_ycpg .submenu_li").removeClass("active");
                        self.curtype = 'mdfb';
                        if (self.fxpgObj) {
                            self.fxpgObj.stop();
                        }
                        self.ictmap.realtarget.hideRealTargetLayer();
                        //add mdfb layer
                        self.addmdfbLayer();
                        self.ictmap.OperateState.wjfx = true;
                    }
                });

                //流量分布
                $menuContainer.find(".submenu_wjanalysis .submenu_li_llfb").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.ictmap.realtarget.addRealTargetLayer();
                        self.ictmap.OperateState.wjfx = false;
                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_ycpg .submenu_li").removeClass("active");
                        self.curtype = 'llfb';
                        if (self.fxpgObj) {
                            self.fxpgObj.stop();
                        }
                        self.ictmap.realtarget.hideRealTargetLayer();
                        // add llfb layer
                        self.addllfbLayer();
                        self.ictmap.OperateState.wjfx = true;
                    }
                });

                //速度分布
                $menuContainer.find(".submenu_wjanalysis .submenu_li_sdfb").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.ictmap.realtarget.addRealTargetLayer();
                        self.ictmap.OperateState.wjfx = false;
                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_ycpg .submenu_li").removeClass("active");
                        self.curtype = 'sdfb';
                        if (self.fxpgObj) {
                            self.fxpgObj.stop();
                        }
                        self.ictmap.realtarget.hideRealTargetLayer();
                        //add sdfb layer
                        self.addsdfbLayer();
                        self.ictmap.OperateState.wjfx = true;
                    }
                });

                //失事分布
                $menuContainer.find(".submenu_wjanalysis .submenu_li_ssfb").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.ictmap.realtarget.addRealTargetLayer();
                        self.ictmap.OperateState.wjfx = false;
                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_ycpg .submenu_li").removeClass("active");
                        self.curtype = 'ssfb';
                        if (self.fxpgObj) {
                            self.fxpgObj.stop();
                        }
                        self.ictmap.realtarget.hideRealTargetLayer();
                        //add ssfb layer
                        self._ssfblayergroup = L.featureGroup();
                        self.ictmap.map.addLayer(self._ssfblayergroup);
                        self.addSsfbLayer();
                        self.ictmap.OperateState.wjfx = true;
                    }
                });

                //活动预测 改为 风险评估
                $menuContainer.find(".submenu_wjanalysis .submenu_li_fxpg").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.ictmap.realtarget.addRealTargetLayer();
                        self.ictmap.OperateState.wjfx = false;
                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_jtms .submenu_li").removeClass("active");
                        self.curtype = 'hdyc';
                        self.ictmap.realtarget.hideRealTargetLayer();
                        if (self.fxpgObj) {
                            self.fxpgObj.stop();
                        }
                        //add hdyc layer
                        self.addHdycLayer();
                        self.ictmap.OperateState.wjfx = true;
                    }
                });

                //风险评估 改为 活动预测
                $menuContainer.find(".submenu_wjanalysis  .submenu_li_hdyc").on("click", function() {
                    var $this = $(this);
                    self.removeLayer();
                    self.fxpgObj = L.ICT.Func["FXPG"].getInstance();
                    if ($this.hasClass("active")) {
                        $this.removeClass("active");
                        self.curtype = null;
                        self.fxpgObj.stop();
                        self.ictmap.OperateState.wjfx = false;
                        self.ictmap.realtarget.addRealTargetLayer();

                    } else {
                        $this.addClass("active").siblings().removeClass("active");
                        $menuContainer.find(".submenu_wjanalysis_jtms .submenu_li").removeClass("active");
                        self.curtype = 'fxpg';
                        self.ictmap.realtarget.hideRealTargetLayer();
                        //run fxpg
                        self.ictmap.OperateState.wjfx = true;
                        self.fxpgObj.start();

                    }
                });
            },

            addSsfbLayer: function() {
                var url = this.config.accidentUrl;
                this.ajax.get(url, null, true, this, function(data, error) {
                    if (this.curtype !== 'ssfb') {
                        return;
                    }
                    if (error) {
                        return;
                    }
                    if (data.state !== 1) {
                        console.log(data.msg.error);
                    }

                    this.displaySsfbData(data);
                });
            },

            displaySsfbData: function(data) {
                var shiplist = data.msg.list;
                if (shiplist.length <= 0) return;
                for (var i = 0, len = shiplist.length; i < len; i++) {
                    var dataobj = shiplist[i];
                    this.convertData(dataobj);
                    var marker = this.createCircleMarker(dataobj);
                    if (!this.ictmap.map.hasLayer(this._ssfblayergroup)) {
                        this._ssfblayergroup = L.featureGroup([]);
                        this.ictmap.map.addLayer(this._ssfblayergroup);
                    }
                    this._ssfblayergroup.addLayer(marker);
                }
            },

            convertData: function(dataobj) {
                dataobj.lon = parseFloat(dataobj.lon / 600000);
                dataobj.lat = parseFloat(dataobj.lat / 600000);
            },

            createCircleMarker: function(dataobj) {
                var latlng = L.latLng(dataobj.lat, dataobj.lon);
                var markerOptions = {
                    radius: 4,
                    stroke: false,
                    fill: true,
                    fillColor: '#f00',
                    opacity: 1,
                    fillOpacity: 1,
                    data: dataobj
                };
                var marker = L.circleMarker(latlng, markerOptions);

                var popup = this.createPopPanel(dataobj);
                marker.bindPopup(popup);
                return marker;
            },

            createPopPanel: function(dataobj) {
                var options = {
                    minWidth: 200,
                    maxWidth: 300
                };
                var popup = L.popup(options);
                var content = this.getPopPanelContent(dataobj);
                popup.setContent(content);
                return popup;
            },

            getPopPanelContent: function(dataobj) {
                var lat = L.ict.app.util.tool.latlngTodfmStr(dataobj.lat, "lat");
                var lng = L.ict.app.util.tool.latlngTodfmStr(dataobj.lon, "lng");
                var time = L.ict.app.util.dateTime.getTimeStrFromUnix(dataobj.tim);
                var html = [];
                html.push('<div style="padding:5px;">');
                html.push('<table>');
                html.push('<tr><td>批号：</td><td>' + dataobj.id + '</td></tr>');
                html.push('<tr><td>经度：</td><td>' + lng + '</td></tr>');
                html.push('<tr><td>纬度：</td><td>' + lat + '</td></tr>');
                html.push('<tr><td>描述：</td><td>' + dataobj.des || '' + '</td></tr>');
                html.push('<tr><td>危险等级：</td><td>' + dataobj.dlev + '</td></tr>');
                html.push('<tr><td>更新时间：</td><td>' + time + '</td></tr>');
                html.push('<tr><td>事件类型：</td><td>' + this.getEvtType(dataobj.itp) + '</td></tr>');
                html.push('<tr><td>更新人：</td><td>' + (dataobj.uby || '未知') + '</td></tr>');
                html.push('</table>');
                html.push('</div>');
                return html.join("");
            },

            getEvtType: function(type) {
                var res = "";
                if (type == 1) {
                    res = "翻船";
                } else if (type == 2) {
                    res = "撞船";
                } else if (type == 3) {
                    res = "海盗";
                } else {
                    res = type;
                }
                return res;
            },

            addHdycLayer: function() {
                var url = this.config.activeForecastUrl;
                var data = {
                    ldlon: -180,
                    ldlat: -90,
                    rulon: 180,
                    rulat: 90
                };
                this.ajax.post(url, data, true, this, function(res, error) {
                    if (this.curtype !== 'hdyc') {
                        return;
                    }
                    if (error) {
                        return;
                    }
                    if (res.state !== 1) {
                        console.log(res.msg);
                        return;
                    }
                    this._activeForecateLayer = L.featureGroup([]);
                    this.ictmap.map.addLayer(this._activeForecateLayer);
                    // this.ictmap.map.setView(L.latLng(19, 112), 6);
                    var render = new L.VectorLabelSvg();
                    for (var i = 0, len = res.msg.list.length; i < len; i++) {
                        var obj = res.msg.list[i];
                        var sw = L.latLng(obj.ldlat / 600000, obj.ldlon / 600000);
                        var ne = L.latLng(obj.rulat / 600000, obj.rulon / 600000);
                        var bounds = L.latLngBounds(sw, ne);
                        var rect = L.rectangle(bounds, {
                            stroke: false,
                            text: obj.dlev,
                            fillColor: this.getBgColorfx(+obj.dlev),
                            fillOpacity: 0.6,
                            renderer: render
                        });
                        this._activeForecateLayer.addLayer(rect);
                    }
                });
            },

            getBgColorfx: function(value) {
                if (value <= 1) {
                    return "#F11415";
                } else if (value > 1 && value <= 5) {
                    return "#FA5E11";
                } else if (value > 5 && value <= 6) {
                    return "#FD910B";
                } else if (value > 6 && value <= 7) {
                    return "#FCCF00";
                } else if (value > 7 && value <= 8) {
                    return "#FFFF85";
                } else if (value > 8 && value <= 9) {
                    return "#4CFF00";
                } else if (value > 9) {
                    return "#91E201";
                }
            },

            addmdfbLayer: function() {
                var url = this.config.mdfbUrl;
                var datajson = {
                    timeout: this.ictmap.realtarget.config.timeout,
                    mode: Project_ParamConfig.CurrentMode
                };
                this.ajax.post(url, datajson, true, this, function(res, error) {
                    if (error) {
                        return;
                    }
                    if (this.curtype !== 'mdfb') {
                        return;
                    }
                    if (res.state !== 1) {
                        return;
                    }
                    var data = res.msg.data;
                    var cfg = {
                        // radius should be small ONLY if scaleRadius is true (or small radius is intended)
                        // if scaleRadius is false it will be the constant radius used in pixels
                        "radius": 2,
                        "maxOpacity": .8,
                        // scales the radius based on map zoom
                        "scaleRadius": true,
                        // if set to false the heatmap uses the global maximum for colorization
                        // if activated: uses the data maximum within the current map boundaries
                        //   (there will always be a red spot with useLocalExtremas true)
                        "useLocalExtrema": true,
                        // which field name in your data represents the latitude - default "lat"
                        latField: 'lat',
                        // which field name in your data represents the longitude - default "lng"
                        lngField: 'lon',
                        // which field name in your data represents the data value - default "value"
                        valueField: 'v'
                    };
                    this._mdfblayer = new HeatmapOverlay(cfg);
                    this.ictmap.map.addLayer(this._mdfblayer);
                    this._mdfblayer.setData({
                        max: 18,
                        data: data
                    });
                });
            },

            addllfbLayer: function() {
                var url = this.config.llfbUrl;
                var data = {
                    timeout: this.ictmap.realtarget.config.timeout,
                    mode: Project_ParamConfig.CurrentMode
                };
                this.ajax.post(url, data, true, this, function(res, error) {
                    if (error) {
                        return;
                    }
                    if (this.curtype !== 'llfb') {
                        return;
                    }
                    if (res.state !== 1) {
                        return;
                    }
                    if (!this.ictmap.map.hasLayer(this._llfblayerGroup)) {
                        this._llfblayerGroup = L.featureGroup().addTo(this.ictmap.map);
                    }
                    // this.ictmap.map.setView(L.latLng(19, 112), 6);

                    this.makeGridll(res.msg.data, this._llfblayerGroup);
                });
            },

            addsdfbLayer: function() {
                var url = this.config.sdfbUrl;
                var data = {
                    timeout: this.ictmap.realtarget.config.timeout,
                    mode: Project_ParamConfig.CurrentMode
                };
                this.ajax.post(url, data, true, this, function(res, error) {
                    if (error) {
                        return;
                    }
                    if (this.curtype !== 'sdfb') {
                        return;
                    }
                    if (res.state !== 1) {
                        return;
                    }
                    if (!this.ictmap.map.hasLayer(this._sdfblayerGroup)) {
                        this._sdfblayerGroup = L.featureGroup().addTo(this.ictmap.map);
                    }
                    // this.ictmap.map.setView(L.latLng(19, 112), 6);

                    this.makeGridsd(res.msg.data, this._sdfblayerGroup);
                });
            },

            makeGridll: function(data, featureGroup) {
                var render = new L.VectorLabelSvg();
                for (var i = 0, len = data.length; i < len; i++) {
                    var obj = data[i];
                    var newlat = obj.lat;
                    var newlon = obj.lon;
                    if (newlat > 90 - 1) {
                        newlat = 90 - 1;
                    }
                    if (newlon > 180 - 1) {
                        newlon = 180 - 1;
                    }
                    var sw = L.latLng(newlat, newlon);
                    var ne = L.latLng(newlat + 1, newlon + 1);
                    var bounds = L.latLngBounds(sw, ne);
                    var rect = L.rectangle(bounds, {
                        stroke: false,
                        text: (obj.v / 10).toFixed(1),
                        fillColor: this.getBgColorll(obj.v / 10),
                        fillOpacity: 0.6,
                        renderer: render
                    });
                    if (this.ictmap.map.hasLayer(featureGroup)) {
                        featureGroup.addLayer(rect);
                    }
                }
            },

            makeGridsd: function(data, featureGroup) {
                var render = new L.VectorLabelSvg();
                for (var i = 0, len = data.length; i < len; i++) {
                    var obj = data[i];
                    var newlat = obj.lat;
                    var newlon = obj.lon;
                    if (newlat > 90 - 1) {
                        newlat = 90 - 1;
                    }
                    if (newlon > 180 - 1) {
                        newlon = 180 - 1;
                    }
                    var sw = L.latLng(newlat, newlon);
                    var ne = L.latLng(newlat + 1, newlon + 1);
                    var bounds = L.latLngBounds(sw, ne);
                    var rect = L.rectangle(bounds, {
                        stroke: false,
                        text: (obj.v / 10).toFixed(1),
                        fillColor: this.getBgColor(obj.v / 10),
                        fillOpacity: 0.6,
                        renderer: render
                    });
                    if (this.ictmap.map.hasLayer(featureGroup)) {
                        featureGroup.addLayer(rect);
                    }
                }
            },

            //根据值获取背景颜色
            getBgColorll: function(value) {
                if (value < 1) {
                    return "#91E201";
                } else if (value >= 1 && value < 10) {
                    return "#009E01";
                } else if (value >= 10 && value < 100) {
                    return "#FCCF00";
                } else if (value >= 100 && value < 1000) {
                    return "#FFFF01";
                } else if (value >= 1000 && value < 10000) {
                    return "#FD910B";
                }
                // else if (value >=10000 && value < 100000) {
                //     return "#FA5E11";
                // }
                else {
                    return "#F11415";
                }
            },

            getBgColor: function(value) {
                if (value <= 1) {
                    return "#91E201";
                } else if (value > 1 && value <= 5) {
                    return "#009E01";
                } else if (value > 5 && value <= 6) {
                    return "#FFFF01";
                } else if (value > 6 && value <= 7) {
                    return "#FCCF00";
                } else if (value > 7 && value <= 8) {
                    return "#FD910B";
                } else if (value > 8 && value <= 9) {
                    return "#FA5E11";
                } else if (value > 9) {
                    return "#F11415";
                }
            },

            removeLayer: function() {
                if (this.ictmap.map.hasLayer(this._layer)) {
                    this.ictmap.map.removeLayer(this._layer);
                    this._layer = null;
                }
                if (this.ictmap.map.hasLayer(this._ssfblayergroup)) {
                    this.ictmap.map.removeLayer(this._ssfblayergroup);
                    this._ssfblayergroup = null;
                }
                if (this.ictmap.map.hasLayer(this._activeForecateLayer)) {
                    this.ictmap.map.removeLayer(this._activeForecateLayer);
                    this._activeForecateLayer = null;
                }
                if (this.ictmap.map.hasLayer(this._mdfblayer)) {
                    this.ictmap.map.removeLayer(this._mdfblayer);
                    this._mdfblayer = null;
                }
                if (this.ictmap.map.hasLayer(this._llfblayerGroup)) {
                    this.ictmap.map.removeLayer(this._llfblayerGroup);
                    this._llfblayerGroup = null;
                }
                if (this.ictmap.map.hasLayer(this._sdfblayerGroup)) {
                    this.ictmap.map.removeLayer(this._sdfblayerGroup);
                    this._sdfblayerGroup = null;
                }
            }
        })

    });

});
